import React, { useMemo, useRef, useState } from 'react';
import { Input, Tabs, InputNumber, Upload, Button, Tooltip, Divider, Modal, Steps, Dropdown, Select, Switch, Popconfirm, message, Row, Col } from 'antd';
import styles from './index.less';
import { ArrowRightOutlined, RetweetOutlined, PlusOutlined, CloseOutlined, LoadingOutlined, LockOutlined, UnlockOutlined } from '@ant-design/icons';
import IconFont from '../IconFont';
import { SketchPicker } from 'react-color';
import { pxConversionMm, mmConversionPx } from "@/utils/transpxmm";
import { useModel } from "umi";
import InitForm from '../InitForm';
import { Scrollbars } from 'react-custom-scrollbars';
import EditTable from '../EditTable';
import Colorpicker from '../Colorpicker';
import { useEffect } from 'react';
import moment from 'moment';
import { useRequest } from 'ahooks';
import { formFetch, getFetch, postFetch } from '@/utils/doFetch';
import html2canvas from 'html2canvas';
import { async } from '@jiaminghi/data-view-react/lib/index-cd27b7f6';


const { TabPane } = Tabs;
const { Step } = Steps;

const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

    if (!isJpgOrPng) {
        message.error('仅支持 JPG/PNG 格式图片!');
    }

    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isLt2M) {
        message.error('图片大小须小于2MB!');
    }

    return isJpgOrPng && isLt2M;
};

const loadImageSize = (url) => {
    return new Promise((resolve, reject) => {
        // 创建对象
        var img = new Image();
        // 改变图片的src
        img.src = url;
        // 判断是否有缓存
        if (img.complete) {
            let percent = (img.height / img.width) ?? 1;
            resolve(percent);
        } else {
            // 加载完成执行
            img.onload = function () {
                let percent = (img.height / img.width) ?? 1;
                resolve(percent);
            };
            img.onerror = function () {
                setTimeout(() => {
                    resolve(1)
                }, 200);
            };
        }

    })
};

const UploadImage = ({ imgurl, setimgurl }) => {
    const [loading, setLoading] = useState(false);
    const handleChange = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }

        if (info.file.status === 'done') {
            setLoading(false)
            // Get this url from response in real world.
            if (info?.file?.response?.data?.origin_url) {
                setimgurl(info?.file?.response?.data?.origin_url ?? null);
            } else {
                message.warn("上传失败")
            }
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div
                style={{
                    marginTop: 8,
                }}
            >
                上传
            </div>
        </div>
    );
    return (
        <Upload
            name="file"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action="/gauss/api/file"
            beforeUpload={beforeUpload}
            onChange={handleChange}
        >
            {imgurl ? (
                <img
                    src={imgurl}
                    alt="图片"
                    style={{
                        width: '100%',
                    }}
                />
            ) : (
                uploadButton
            )}
        </Upload>
    );
};

//base64转file
function dataURLtoBlob(dataurl, name) {
    let arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], name, {
        type: mime,
    })
}

function Canvas({ config, setconfig }) {
    const [checked, setchecked] = useState();

    let cur = useMemo(() => {
        let actives = config?.pages ? config?.pages.filter(it => it.active)[0] : {};
        if (actives.width == 1920 && actives.height == 1080 && actives.unit == "px") {
            setchecked("cpu");
        } else if (actives.width == 1280 && actives.height == 2778 && actives.unit == "px") {
            setchecked("phone");
        } else if (actives.width == 210 && actives.height == 297 && actives.unit == "mm") {
            setchecked("A4");
        }
        return actives
    }, [config])

    //修改页面尺寸
    let changepagesize = (width, height, unit) => {
        setconfig(s => {
            let newcf = { ...s };
            newcf.pages = newcf.pages.map(it => {
                if (it.active) {
                    it.width = width ? width : it.width ? it.width : newcf.width;
                    it.height = height ? height : it.height ? it.height : newcf.height;
                    it.unit = unit ? unit : it.unit ? it.unit : "px";
                }
                return it
            })
            return newcf;
        })
    }

    return (
        config?.id ?
            <div style={{ userSelect: "none" }}>
                <p className={`${styles.title} spread`}>
                    <span>
                        页面设置
                    </span>
                    <a
                        onClick={async () => {
                            let poster = document.getElementById("poster")
                            let canvas = await html2canvas(poster, {
                                scale: 3,
                                allowTaint: true
                            });
                            let imgData = canvas.toDataURL('image/jpeg', 1.0);
                            // Modal.info({
                            //     title:"112",
                            //     content:<img src={imgData}/>
                            // })
                            let file = dataURLtoBlob(imgData, "poster.jpg");
                            let params = new FormData();
                            params.append("file", file);
                            formFetch({ url: "/api/file", params }).then(res => {
                                if (res.code == 0) {
                                    if (res?.data?.preview_url) {
                                        postFetch({
                                            url: "/api/template/update_poster", params: {
                                                id: config.id,
                                                poster: res?.data?.preview_url
                                            }, method: "PUT"
                                        }).then(res => {
                                            if (res.code == 0) {
                                                message.success("设置成功!");
                                            }
                                        })
                                    }

                                }

                            })
                        }}
                    >
                        本页设为封面
                    </a>
                </p>
                <Divider style={{ marginTop: 0, marginBottom: 12 }}></Divider>
                <p style={{ fontSize: 14, color: "#999", display: "flex" }}>
                    <span style={{ marginRight: 12 }}>
                        常规尺寸
                    </span>
                </p>
                <div className={`${styles.icons} center column`} style={{ justifyContent: "space-between" }}>
                    <div
                        className={checked == "cpu" ? styles.active : 'row'}
                        onClick={() => {
                            if (checked == "cpu") {
                                changepagesize();
                                setchecked("")
                            } else {
                                changepagesize(1920, 1080, "px");
                                setchecked("cpu");
                            }
                        }}>
                        <div style={{ width: 36 }} className='center'>
                            <IconFont type='icon-cpu' style={{ fontSize: 34, color: "#fff" }} />
                        </div>
                        <p style={{ marginRight: 12 }}>电脑尺寸</p>
                        <span style={{ flex: 1, textAlign: "right" }}>1920*1080像素</span>
                    </div>
                    <div className={checked == "phone" ? styles.active : 'row'} onClick={() => {
                        if (checked == "phone") {
                            changepagesize();
                            setchecked("")
                        } else {
                            changepagesize(1280, 2778, "px");
                            setchecked("phone");
                        }
                    }} style={{ margin: "12px 0" }}>
                        <div style={{ width: 36 }} className='center'>
                            <IconFont type='icon-phone' style={{ fontSize: 36, color: "#fff", paddingRight: 2 }} />
                        </div>
                        <p>手机尺寸</p>
                        <span style={{ flex: 1, textAlign: "right" }}>1280*2778像素</span>
                    </div>
                    <div className={checked == "A4" ? styles.active : 'row'} onClick={() => {
                        if (checked == "A4") {
                            changepagesize();
                            setchecked("")
                        } else {
                            changepagesize(210, 297, "mm");
                            setchecked("A4");
                        }
                    }}>
                        <div style={{ width: 36 }} className='center'>
                            <IconFont type='icon-A4' style={{ fontSize: 32 }} />
                        </div>
                        <p>A4尺寸</p>
                        <span style={{ flex: 1, textAlign: "right" }}>210*297毫米</span>
                    </div>
                </div>
                <Divider style={{ marginTop: 12, marginBottom: 12 }}></Divider>
                <p style={{ fontSize: 14, color: "#999", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span style={{ marginRight: 12 }}>
                        自定义尺寸
                    </span>
                </p>

                <div className="row" style={{ justifyContent: "space-around" }}>
                    <InputNumber
                        value={cur.width ? parseInt(cur.width) : config?.width}
                        onChange={(val) => {
                            changepagesize(val, null);
                        }} style={{

                        }}>

                    </InputNumber>
                    <Tooltip title="宽高互换">
                        <RetweetOutlined style={{ fontSize: 18, color: "#000000", padding: 2 }} onClick={() => {
                            let width = cur.width ? cur.width : config?.width,
                                height = cur.height ? cur.height : config?.height;
                            changepagesize(height, width, null);
                        }} />
                    </Tooltip>
                    <InputNumber
                        value={cur.height ? parseInt(cur.height) : config?.height}
                        onChange={(val) => {
                            changepagesize(null, val);
                        }} style={{

                        }}
                    ></InputNumber>
                    <Select
                        options={[
                            {
                                label: "像素",
                                value: "px"
                            },
                            {
                                label: "毫米",
                                value: "mm"
                            }
                        ]}
                        value={cur.unit ?? "px"}
                        onChange={(val) => {
                            let width = cur.width ? cur.width : config?.width,
                                height = cur.height ? cur.height : config?.height;
                            if (val == "px") {
                                width = mmConversionPx(width);
                                height = mmConversionPx(height);
                            } else {
                                width = pxConversionMm(width);
                                height = pxConversionMm(height);
                            }
                            changepagesize(width, height, val);

                        }}
                    ></Select>


                </div>


                <Divider style={{ margin: "20px 0 12px 0" }}></Divider>
                <p style={{ fontSize: 14, color: "#999", display: "flex" }}>
                    <span style={{ marginRight: 12 }}>
                        页面背景
                    </span>
                </p>

                <Dropdown placement="bottomRight" overlay={<SketchPicker
                    style={{ width: "100%" }}
                    color={cur.backgroundColor}
                    onChangeComplete={(color) => {
                        setconfig(s => {
                            let newcf = { ...s };
                            newcf.pages = newcf.pages.map(it => {
                                if (it.active) {
                                    it.backgroundColor = `rgba(${color.rgb.r},${color.rgb.g},${color.rgb.b},${color.rgb.a})`;
                                }
                                return it
                            })
                            return newcf;
                        })
                    }}
                />}>
                    <div className="center">
                        <div className={styles.color}>
                            <div style={{ backgroundColor: cur.backgroundColor }}>

                            </div>
                        </div>
                    </div>
                </Dropdown>
            </div> :
            <div>
                <p>
                    创建您的模板
                </p>
                <Divider style={{ margin: "0 0 12px 0" }}></Divider>
                <div>
                    <Steps progressDot current={5} direction="vertical">
                        <Step title="步骤一" description="点击左侧模板菜单" />
                        <Step title="步骤二" description={<span>选择你想要的尺寸点击<Button style={{ margin: "0 12px" }} icon={<ArrowRightOutlined />} shape="circle" size='small' />按钮</span>} />
                        <Step title="创建成功" description="恭喜你！成功创建自己的模板！" />
                    </Steps>
                </div>
            </div>
    );
}

const fontFamilyconfig = [
    {
        label: "OPPOSans",
        value: "OPPOSans"
    },
    {
        label: "资源圆体",
        value: "ResourceHanRounded"
    },
    {
        label: "普惠体",
        value: "puhui"
    },
    {
        label: "思源黑体",
        value: "syh"
    },
    {
        label: "思源宋体",
        value: "sc"
    },
    {
        label: "思源宋体FandolFang",
        value: "FandolFang"
    },
]

function Rowtext({ config, setconfig, initialState, setInitialState }) {
    const { componentConfig } = initialState,
        { fontSize, color, fontWeight, lineHeight, backgroundColor, textAlign, borderRadius, fontFamily } = componentConfig?.style ?? {};


    return <div>
        <p className={styles.title} style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span>
                文本框设置
            </span>
        </p>
        <Divider style={{ marginTop: 0, marginBottom: 12 }}></Divider>
        <InitForm
            style={{ marginTop: -24 }}
            fields={{
                "fontFamily": {
                    "value": fontFamily,
                    "type": "select",
                    "title": "字体",
                    "name": [
                        "fontFamily"
                    ],
                    "required": false,
                    "options": [
                        {
                            label: "默认",
                            value: ""
                        },
                        ...fontFamilyconfig
                    ]
                },
                "fontSize": {
                    "value": fontSize,
                    "type": "slider",
                    "title": "字体大小",
                    "name": [
                        "fontSize"
                    ],
                    "required": false
                },
                "color": {
                    "value": color,
                    "type": "colorpicker",
                    "title": "字体颜色",
                    "name": [
                        "color"
                    ],
                    "required": false
                },
                "fontWeight": {
                    "value": fontWeight ?? "normal",
                    "type": "radio",
                    "title": "字体粗细",
                    "name": [
                        "fontWeight"
                    ],
                    "required": false,
                    "options": [
                        {
                            "label": "细",
                            "value": "lighter"
                        },
                        {
                            "label": "中",
                            "value": "normal"
                        },
                        {
                            "label": "粗",
                            "value": "bolder"
                        }
                    ]
                },
                "lineHeight": {
                    "value": lineHeight,
                    "type": "slider",
                    "title": "行间距",
                    "name": [
                        "lineHeight"
                    ],
                    "step": 0.25,
                    "min": 1,
                    "max": 10,
                    "required": false
                },
                "textAlign": {
                    "value": textAlign,
                    "type": "radio",
                    "title": "水平对齐方式",
                    "name": [
                        "textAlign"
                    ],
                    "required": false,
                    "options": [
                        {
                            "label": "左",
                            "value": "left"
                        },
                        {
                            "label": "中",
                            "value": "center"
                        },
                        {
                            "label": "右",
                            "value": "right"
                        }
                    ]
                },
                "backgroundColor": {
                    "value": backgroundColor,
                    "type": "colorpicker",
                    "title": "区块背景",
                    "name": [
                        "backgroundColor"
                    ],
                    "transparent": true,
                    "required": false
                },
                "borderRadius": {
                    "value": borderRadius,
                    "type": "slider",
                    "title": "区块圆角",
                    "name": [
                        "borderRadius"
                    ],
                    "max": 400,
                    "required": false
                }
            }}
            col={{ span: 24 }}
            actions={() => null}
            onChange={(val, vals) => {
                setconfig((config) => {
                    let newconfig = JSON.parse(JSON.stringify(config));
                    newconfig.pages = newconfig?.pages?.map?.(item => {
                        if (item.active) {
                            item.components = item?.components?.map?.(its => {
                                if (its.id == componentConfig.id) {
                                    its.style = {
                                        ...its.style,
                                        ...val
                                    }
                                    setInitialState(s => ({ ...s, componentConfig: its }))//更新当前选中值
                                }
                                return its;
                            })
                        }
                        return item
                    });
                    return newconfig
                });
            }}

        ></InitForm>
    </div>
}

function Columntext({ config, setconfig, initialState, setInitialState }) {
    const { componentConfig } = initialState,
        { fontSize, color, fontWeight, lineHeight, backgroundColor, textAlign, borderRadius, fontFamily } = componentConfig?.style ?? {};


    return <div>
        <p className={styles.title} style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span>
                文本框设置
            </span>
        </p>
        <Divider style={{ marginTop: 0, marginBottom: 12 }}></Divider>
        <InitForm
            style={{ marginTop: -24 }}
            fields={{
                "fontFamily": {
                    "value": fontFamily,
                    "type": "select",
                    "title": "字体",
                    "name": [
                        "fontFamily"
                    ],
                    "required": false,
                    "options": [
                        {
                            label: "默认",
                            value: ""
                        },
                        {
                            label: "Aa剑豪体",
                            value: "jianhao"
                        },
                    ]
                },
                "fontSize": {
                    "value": fontSize,
                    "type": "slider",
                    "title": "字体大小",
                    "name": [
                        "fontSize"
                    ],
                    "required": false
                },
                "color": {
                    "value": color,
                    "type": "colorpicker",
                    "title": "字体颜色",
                    "name": [
                        "color"
                    ],
                    "required": false
                },
                "fontWeight": {
                    "value": fontWeight,
                    "type": "radio",
                    "title": "字体粗细",
                    "name": [
                        "fontWeight"
                    ],
                    "required": false,
                    "options": [
                        {
                            "label": "细",
                            "value": "lighter"
                        },
                        {
                            "label": "中",
                            "value": "normal"
                        },
                        {
                            "label": "粗",
                            "value": "bolder"
                        }
                    ]
                },
                "lineHeight": {
                    "value": lineHeight,
                    "type": "slider",
                    "title": "行间距",
                    "name": [
                        "lineHeight"
                    ],
                    "required": false
                },
                "textAlign": {
                    "value": textAlign,
                    "type": "radio",
                    "title": "垂直对齐方式",
                    "name": [
                        "textAlign"
                    ],
                    "required": false,
                    "options": [
                        {
                            "label": "上",
                            "value": "left"
                        },
                        {
                            "label": "中",
                            "value": "center"
                        },
                        {
                            "label": "下",
                            "value": "right"
                        }
                    ]
                },
                "backgroundColor": {
                    "value": backgroundColor,
                    "type": "colorpicker",
                    "title": "区块背景",
                    "name": [
                        "backgroundColor"
                    ],
                    "transparent": true,
                    "required": false
                },
                "borderRadius": {
                    "value": borderRadius,
                    "type": "slider",
                    "title": "区块圆角",
                    "name": [
                        "borderRadius"
                    ],
                    "max": 400,
                    "required": false
                }
            }}
            col={{ span: 24 }}
            actions={() => null}
            onChange={(val, vals) => {
                setconfig((config) => {
                    let newconfig = JSON.parse(JSON.stringify(config));
                    newconfig.pages = newconfig?.pages?.map?.(item => {
                        if (item.active) {
                            item.components = item?.components?.map?.(its => {
                                if (its.id == componentConfig.id) {
                                    its.style = {
                                        ...its.style,
                                        ...val
                                    }
                                    setInitialState(s => ({ ...s, componentConfig: its }))//更新当前选中值
                                }
                                return its;
                            })
                        }
                        return item
                    });
                    return newconfig
                });
            }}

        ></InitForm>
    </div>
}

function Linechart({ config, setconfig, initialState, setInitialState, bianliang }) {
    const { componentConfig, curselected } = initialState,
        { fontSize, fontWeight, lineHeight, backgroundColor, textAlign, borderRadius, fontFamily } = componentConfig?.style ?? {},
        { color, yAxis, series } = componentConfig?.option ?? {}
    const [activeKey, setactiveKey] = useState("0");


    const [yaxis, setyaxis] = useState(yAxis?.data?.map(it => ({
        name: it,
        id: it
    })));
    const [xaxis, setxaxis] = useState([{
        name: "",
        value: 0,
    }]);

    function refreshconfig(fn) {
        setconfig((config) => {
            let newconfig = JSON.parse(JSON.stringify(config));
            newconfig.pages = newconfig?.pages?.map?.(item => {
                if (item.active) {
                    item.components = item?.components?.map?.(its => {
                        if (its.id == componentConfig.id) {
                            return fn?.(its);
                        }
                        return its;
                    })
                }
                return item
            });
            return newconfig
        });
    }

    //tab切换改变表格数据
    useEffect(() => {
        if (activeKey == "Y") {
            return
        }
        let cur = parseInt(activeKey);//第几个
        let dataSource = yAxis?.data ? yAxis.data.map((it, i) => {
            let typelist = series[cur]["typelist"] ?? {}
            return {
                name: it,
                value: series[cur]["data"][i],
                type: typelist[it]
            }
        }) : [];
        //按照从大到小排序
        // dataSource.sort((a, b) => {
        //     return b.value - a.value
        // })
        setxaxis(dataSource);
    }, [activeKey, curselected]);


    let edittablepropsy = useMemo(() => {
        refreshconfig(vals => {
            vals.option = {
                ...vals.option,
                yAxis: {
                    ...vals.option.yAxis,
                    data: yaxis.map(it => {
                        return it.name ?? ''
                    })
                }
            }
            setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
            return vals
        })
        return {
            "value": yaxis,
            "type": "edittable",
            "columns": [
                {
                    title: "Y轴名称",
                    dataIndex: "name",
                    key: "name",
                },
                {
                    title: "操作",
                    valueType: "option",
                    width: 50
                },
            ],
            "rowKey": "id",
            "rowName": "id",
            "onChange": (value) => {
                setyaxis(value)
            }
        }
    }, [yaxis])


    let edittableprops = useMemo(() => {
        if (activeKey == "Y") {
        } else {
            let cur = parseInt(activeKey);//第几个
            refreshconfig(vals => {
                vals.option = {
                    ...vals.option,
                    series: vals.option.series.map((it, i) => {
                        if (cur == i) {
                            console.log(xaxis);
                            it.data = xaxis.map(item => item.value);
                        }
                        return it
                    })
                }
                setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                return vals
            })
        }
        return {
            "maxLength": yAxis?.data.length,
            "value": xaxis,
            "type": "edittable",
            "columns": [
                {
                    title: "",
                    dataIndex: "index",
                    key: "index",
                    editable: false,
                    width: 30,
                    render: (text, record) => {
                        const IconLocker = record.type ? LockOutlined : UnlockOutlined;
                        return <Tooltip title={"切换本行数据来源 - " + (!record.type ? "输入" : "变量")} placement="bottomLeft">
                            <IconLocker style={{ color: record.type ? "#1dac57" : "#ff4800" }} onClick={() => {
                                refreshconfig((its) => {
                                    its.option = {
                                        ...its.option,
                                        series: its.option.series.map((cur, ins) => {
                                            if (activeKey == ins) {
                                                cur.typelist = {
                                                    ...cur.typelist,
                                                    [record.name]: !record.type
                                                }
                                            }
                                            return cur
                                        })
                                    }
                                    setInitialState(s => ({ ...s, componentConfig: its }))//更新当前选中值
                                    return its
                                })
                                setxaxis((xaxis) => {
                                    let newx = [...xaxis];
                                    newx = newx.map(it => {
                                        if (it.name == record.name) {
                                            it.type = !record.type;
                                        }
                                        return it
                                    })

                                    return newx
                                })
                            }} />
                        </Tooltip>
                    }
                },
                {
                    title: "名称",
                    dataIndex: "name",
                    key: "name",
                    width: 100,
                    editable: false

                },
                {
                    title: "值",
                    dataIndex: "value",
                    key: "value",
                    valueType: (record) => {
                        return record.type ? "select" : "input"
                    },
                    request: () => {
                        return bianliang.map(its => ({
                            label: its.variable_name,
                            value: `{{${its.variable_name}}}`
                        }))
                    }

                },
            ],
            "rowKey": "name",
            "rowName": "name",
            "onChange": (value) => {
                setxaxis(value)
            }
        }
    }, [xaxis])


    return <div>
        <p className={styles.title} style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span>
                条形图设置
            </span>
        </p>
        <Divider style={{ marginTop: 0, marginBottom: 12 }}></Divider>

        <InitForm
            style={{ marginTop: -24 }}
            fields={{
                "backgroundColor": {
                    "value": backgroundColor,
                    "type": "colorpicker",
                    "title": "区块背景",
                    "name": [
                        "backgroundColor"
                    ],
                    "transparent": true,
                    "required": false
                },
                "borderRadius": {
                    "value": borderRadius,
                    "type": "slider",
                    "title": "区块圆角",
                    "name": [
                        "borderRadius"
                    ],
                    "max": 400,
                    "required": false
                },
            }}
            col={{ span: 24 }}
            actions={() => null}
            onChange={(val, vals) => {
                refreshconfig((its) => {
                    its.style = {
                        ...its.style,
                        backgroundColor: vals.backgroundColor,
                        borderRadius: vals.borderRadius
                    }
                    setInitialState(s => ({ ...s, componentConfig: its }))//更新当前选中值
                    return its
                })
            }}

        ></InitForm>

        <div style={{ margin: "-36px 0px 0 0px" }}>
            <b style={{ color: "#000" }} className='spread'>
                <span>编辑数据</span>
            </b>
            <Tabs
                activeKey={activeKey}
                tabBarGutter={12}
                onChange={(index) => {
                    setactiveKey(index)
                }}
                tabBarExtraContent={{
                    right: <Tooltip title={"添加维度(条形图上的条)"} placement="topRight">
                        <Button size='small' type='primary' icon={<PlusOutlined />} onClick={() => {
                            refreshconfig(vals => {
                                vals.option.color.push("#666666");
                                vals.option.series.push({
                                    name: '新增',
                                    type: 'bar',
                                    label: {
                                        show: true,
                                        formatter: '{c}',
                                        align: "left",
                                        textStyle: {
                                            fontSize: 16
                                        }
                                    },
                                    data: [18203, 23489, 29034, 104970, 131744, 630230]
                                })
                                setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                                return vals
                            })
                        }} />
                    </Tooltip>
                }}
            >
                <TabPane
                    tab={<a>编辑Y轴</a>}
                    key={"Y"}
                    active={false}
                >
                    <EditTable {...edittablepropsy}></EditTable>
                </TabPane>
                {
                    series ? series.map((item, index) => {
                        return <TabPane
                            tab={<div className='center'>
                                {item.name}
                                {
                                    index == 0 ? null : <Popconfirm
                                        title="是否删除该维度"
                                        okText="删除"
                                        onConfirm={() => {
                                            refreshconfig(vals => {
                                                vals.option = {
                                                    ...vals.option,
                                                    color: vals.option.color?.filter((a, i) => i != index),
                                                    series: vals.option.series?.filter((a, i) => i != index)
                                                }
                                                setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                                                return JSON.parse(JSON.stringify(vals))
                                            })
                                            setactiveKey((s) => {
                                                let news = parseInt(s);
                                                return news == 0 ? "0" : (news - 1).toString();
                                            })
                                        }}
                                    >
                                        <CloseOutlined style={{ margin: 0, marginLeft: 6, fontSize: 12 }}>
                                        </CloseOutlined>
                                    </Popconfirm>
                                }

                            </div>}
                            key={index}>
                            <label htmlFor="titles" style={{ margin: "0 0 12px 0", display: "block" }}>维度/条形名称</label>
                            <Input
                                name="titles"
                                value={item.name}
                                onChange={e => {
                                    let val = e.target.value;
                                    refreshconfig((vals) => {
                                        vals.option = {
                                            ...vals.option,
                                            series: series.map((it, i) => {
                                                if (i == index) {
                                                    it.name = val
                                                }
                                                return it
                                            })
                                        }
                                        setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                                        return vals
                                    })
                                }} />
                            <label style={{ margin: "12px 0 12px 0", display: "block" }}>条形颜色</label>
                            <Colorpicker
                                value={color[index]}
                                style={{ marginBottom: 28 }}
                                onChange={val => {
                                    refreshconfig((vals) => {
                                        vals.option = {
                                            ...vals.option,
                                            color: color.map((it, i) => {
                                                if (i == index) {
                                                    it = val
                                                }
                                                return it
                                            })
                                        }
                                        setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                                        return vals
                                    })
                                }} />

                            <EditTable {...edittableprops}></EditTable>
                        </TabPane>
                    }) : null
                }

            </Tabs>

        </div>




    </div>
}

function Barchart({ config, setconfig, initialState, setInitialState, bianliang }) {
    const { componentConfig, curselected } = initialState,
        { fontSize, fontWeight, lineHeight, backgroundColor, textAlign, borderRadius, fontFamily } = componentConfig?.style ?? {},
        { color, xAxis, series } = componentConfig?.option ?? {}
    const [activeKey, setactiveKey] = useState("0");

    const [yaxis, setyaxis] = useState(xAxis?.data?.map(it => ({
        name: it,
        id: it
    })));
    const [xaxis, setxaxis] = useState([{
        name: "",
        value: 0,
    }]);

    function refreshconfig(fn) {
        setconfig((config) => {
            let newconfig = JSON.parse(JSON.stringify(config));
            newconfig.pages = newconfig?.pages?.map?.(item => {
                if (item.active) {
                    item.components = item?.components?.map?.(its => {
                        if (its.id == componentConfig.id) {
                            return fn?.(its);
                        }
                        return its;
                    })
                }
                return item
            });
            return newconfig
        });
    }

    //tab切换改变表格数据
    useEffect(() => {
        if (activeKey == "Y") {
            return
        }
        let cur = parseInt(activeKey);//第几个
        let dataSource = xAxis?.data ? xAxis.data.map((it, i) => {
            let typelist = series[cur]["typelist"] ?? {}
            return {
                name: it,
                value: series[cur]["data"][i],
                type: typelist[it]
            }
        }) : [];
        //按照从大到小排序
        // dataSource.sort((a, b) => {
        //     return b.value - a.value
        // })
        setxaxis(dataSource);
    }, [activeKey, curselected])

    let edittablepropsy = useMemo(() => {
        refreshconfig(vals => {
            vals.option = {
                ...vals.option,
                xAxis: {
                    ...vals.option.xAxis,
                    data: yaxis.map(it => {
                        return it.name ?? ''
                    })
                }
            }
            setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
            return vals
        })
        return {
            "value": yaxis,
            "type": "edittable",
            "columns": [
                {
                    title: "X轴名称",
                    dataIndex: "name",
                    key: "name",
                },
                {
                    title: "操作",
                    valueType: "option",
                    width: 50
                },
            ],
            "rowKey": "id",
            "rowName": "id",
            "onChange": (value) => {
                setyaxis(value)
            }
        }
    }, [yaxis])


    let edittableprops = useMemo(() => {
        if (activeKey == "Y") {
        } else {
            let cur = parseInt(activeKey);//第几个
            refreshconfig(vals => {
                vals.option = {
                    ...vals.option,
                    series: vals.option.series.map((it, i) => {
                        if (cur == i) {
                            it.data = xaxis.map(item => item.value);
                        }
                        return it
                    })
                }
                setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                return vals
            })
        }
        return {
            "maxLength": xAxis?.data.length,
            "value": xaxis,
            "type": "edittable",
            "columns": [
                {
                    title: "",
                    dataIndex: "index",
                    key: "index",
                    editable: false,
                    width: 30,
                    render: (text, record) => {
                        let IconLocker = record.type ? LockOutlined : UnlockOutlined;
                        return <Tooltip title={"切换本行数据来源 - " + (!record.type ? "输入" : "变量")} placement="bottomLeft">
                            <IconLocker style={{ color: record.type ? "#1dac57" : "#ff4800" }} onClick={() => {
                                refreshconfig((its) => {
                                    its.option = {
                                        ...its.option,
                                        series: its.option.series.map((cur, ins) => {
                                            if (activeKey == ins) {
                                                cur.typelist = {
                                                    ...cur.typelist,
                                                    [record.name]: !record.type
                                                }
                                            }
                                            return cur
                                        })
                                    }
                                    setInitialState(s => ({ ...s, componentConfig: its }))//更新当前选中值
                                    return its
                                })
                                setxaxis((xaxis) => {
                                    let newx = [...xaxis];
                                    newx = newx.map(it => {
                                        if (it.name == record.name) {
                                            it.type = !record.type;
                                        }
                                        return it
                                    })

                                    return newx
                                })

                            }} />
                        </Tooltip>
                    }
                },
                {
                    title: "名称",
                    dataIndex: "name",
                    key: "name",
                    width: 100,
                    editable: false

                },
                {
                    title: "值",
                    dataIndex: "value",
                    key: "value",
                    valueType: (record) => {
                        return record.type ? "select" : "input"
                    },
                    request: () => {
                        return bianliang.map(its => ({
                            label: its.variable_name,
                            value: `{{${its.variable_name}}}`
                        }))
                    }

                },
            ],
            "rowKey": "name",
            "rowName": "name",
            "onChange": (value) => {
                setxaxis(value)
            }
        }
    }, [xaxis])


    return <div>
        <p className={styles.title} style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span>
                条形图设置
            </span>
        </p>
        <Divider style={{ marginTop: 0, marginBottom: 12 }}></Divider>

        <InitForm
            style={{ marginTop: -24 }}
            fields={{
                "backgroundColor": {
                    "value": backgroundColor,
                    "type": "colorpicker",
                    "title": "区块背景",
                    "name": [
                        "backgroundColor"
                    ],
                    "transparent": true,
                    "required": false
                },
                "borderRadius": {
                    "value": borderRadius,
                    "type": "slider",
                    "title": "区块圆角",
                    "name": [
                        "borderRadius"
                    ],
                    "max": 400,
                    "required": false
                },
            }}
            col={{ span: 24 }}
            actions={() => null}
            onChange={(val, vals) => {
                refreshconfig((its) => {
                    its.style = {
                        ...its.style,
                        backgroundColor: vals.backgroundColor,
                        borderRadius: vals.borderRadius
                    }
                    setInitialState(s => ({ ...s, componentConfig: its }))//更新当前选中值
                    return its
                })
            }}

        ></InitForm>

        <div style={{ margin: "-36px 0px 0 0px" }}>
            <b style={{ color: "#000" }} className='spread'>
                <span>编辑数据</span>
            </b>
            <Tabs
                activeKey={activeKey}
                tabBarGutter={12}
                onChange={(index) => {
                    setactiveKey(index)
                }}
                tabBarExtraContent={{
                    right: <Tooltip title={"添加维度(柱状图上的条)"} placement="topRight">
                        <Button size='small' type='primary' icon={<PlusOutlined />} onClick={() => {
                            refreshconfig(vals => {
                                vals.option.color.push("#666666");
                                vals.option.series.push({
                                    name: '新增',
                                    type: 'bar',
                                    label: {
                                        show: true,
                                        formatter: '{c}',
                                        align: "center",
                                        textStyle: {
                                            fontSize: 16
                                        }
                                    },
                                    data: [18203, 23489, 29034, 104970, 131744, 630230]
                                })
                                setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                                return vals
                            })
                        }} />
                    </Tooltip>
                }}
            >
                <TabPane
                    tab={<a>编辑X轴</a>}
                    key={"Y"}
                    active={false}
                >
                    <EditTable {...edittablepropsy}></EditTable>
                </TabPane>
                {
                    series ? series.map((item, index) => {
                        return <TabPane
                            tab={<div className='center'>
                                {item.name}
                                {
                                    index == 0 ? null : <Popconfirm
                                        title="是否删除该维度"
                                        okText="删除"
                                        onConfirm={() => {
                                            refreshconfig(vals => {
                                                vals.option = {
                                                    ...vals.option,
                                                    color: vals.option.color?.filter((a, i) => i != index),
                                                    series: vals.option.series?.filter((a, i) => i != index)
                                                }
                                                setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                                                return JSON.parse(JSON.stringify(vals))
                                            })
                                            setactiveKey((s) => {
                                                let news = parseInt(s);
                                                return news == 0 ? "0" : (news - 1).toString();
                                            })
                                        }}
                                    >
                                        <CloseOutlined style={{ margin: 0, marginLeft: 6, fontSize: 12 }}>
                                        </CloseOutlined>
                                    </Popconfirm>
                                }

                            </div>}
                            key={index}>
                            <label htmlFor="titles" style={{ margin: "0 0 12px 0", display: "block" }}>维度/条形名称</label>
                            <Input
                                name="titles"
                                value={item.name}
                                onChange={e => {
                                    let val = e.target.value;
                                    refreshconfig((vals) => {
                                        vals.option = {
                                            ...vals.option,
                                            series: series.map((it, i) => {
                                                if (i == index) {
                                                    it.name = val
                                                }
                                                return it
                                            })
                                        }
                                        setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                                        return vals
                                    })
                                }} />
                            <label style={{ margin: "12px 0 12px 0", display: "block" }}>条形颜色</label>
                            <Colorpicker
                                value={color[index]}
                                style={{ marginBottom: 28 }}
                                onChange={val => {
                                    refreshconfig((vals) => {
                                        vals.option = {
                                            ...vals.option,
                                            color: color.map((it, i) => {
                                                if (i == index) {
                                                    it = val
                                                }
                                                return it
                                            })
                                        }
                                        setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                                        return vals
                                    })
                                }} />

                            <EditTable {...edittableprops}></EditTable>
                        </TabPane>
                    }) : null
                }

            </Tabs>

        </div>




    </div>
}

function Radarchart({ config, setconfig, initialState, setInitialState, bianliang }) {
    const { componentConfig, curselected } = initialState,
        { fontSize, fontWeight, lineHeight, backgroundColor, textAlign, borderRadius, fontFamily } = componentConfig?.style ?? {},
        { color, radar, series } = componentConfig?.option ?? {};


    const [activeKey, setactiveKey] = useState("0");

    const [yaxis, setyaxis] = useState(radar?.indicator?.map(it => ({
        name: it.name,
        max: it.max,
        id: it.name
    })));

    const [xaxis, setxaxis] = useState([
        {
            name: "",
            value: 0,
        }
    ]);

    function refreshconfig(fn) {
        setconfig((config) => {
            let newconfig = JSON.parse(JSON.stringify(config));
            newconfig.pages = newconfig?.pages?.map?.(item => {
                if (item.active) {
                    item.components = item?.components?.map?.(its => {
                        if (its.id == componentConfig.id) {
                            return fn?.(its);
                        }
                        return its;
                    })
                }
                return item
            });
            return newconfig
        });
    }

    //tab切换改变表格数据
    useEffect(() => {
        if (activeKey == "Y") {
            return
        }
        let cur = parseInt(activeKey);//第几个
        let dataSource = radar?.indicator ? radar?.indicator.map((it, i) => {

            let typelist = series[0]["data"][cur]["typelist"] ?? {}
            return {
                name: it?.name,
                value: series[0]["data"][cur]["value"][i],
                type: typelist[it]
            }
        }) : [];
        //按照从大到小排序
        // dataSource.sort((a, b) => {
        //     return b.value - a.value
        // })
        setxaxis(dataSource);
    }, [activeKey, curselected])

    let edittablepropsy = useMemo(() => {
        refreshconfig(vals => {
            vals.option = {
                ...vals.option,
                radar: {
                    ...vals.option.radar,
                    indicator: yaxis
                }
            }
            setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
            return vals
        })
        return {
            "value": yaxis,
            "type": "edittable",
            "columns": [
                {
                    title: "X轴名称",
                    dataIndex: "name",
                    key: "name",
                },
                {
                    title: "最大值",
                    dataIndex: "max",
                    key: "max",
                },
                {
                    title: "操作",
                    valueType: "option",
                    width: 50
                },
            ],
            "rowKey": "id",
            "rowName": "id",
            "onChange": (value) => {
                setyaxis(value)
            }
        }
    }, [yaxis])


    let edittableprops = useMemo(() => {
        if (activeKey == "Y") {
        } else {
            let cur = parseInt(activeKey);//第几个
            refreshconfig(vals => {
                vals.option = {
                    ...vals.option,
                    series: vals.option.series.map((it, i) => {
                        it.data = it?.data?.map((its, ins) => {
                            if (cur == ins) {
                                its.value = xaxis.map(item => item.value);
                            }
                            return its
                        })
                        return it
                    })
                }
                setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                return vals
            })
        }
        return {
            "maxLength": radar?.indicator?.length ?? 0,
            "value": xaxis,
            "type": "edittable",
            "columns": [
                {
                    title: "",
                    dataIndex: "index",
                    key: "index",
                    editable: false,
                    width: 30,
                    render: (text, record) => {
                        let IconLocker = record.type ? LockOutlined : UnlockOutlined;
                        return <Tooltip title={"切换本行数据来源 - " + (!record.type ? "输入" : "变量")} placement="bottomLeft">
                            <IconLocker style={{ color: record.type ? "#1dac57" : "#ff4800" }} onClick={() => {
                                refreshconfig((its) => {
                                    its.option = {
                                        ...its.option,
                                        series: its.option.series.map((cur, ins) => {
                                            if (activeKey == ins) {
                                                cur.typelist = {
                                                    ...cur.typelist,
                                                    [record.name]: !record.type
                                                }
                                            }
                                            return cur
                                        })
                                    }
                                    setInitialState(s => ({ ...s, componentConfig: its }))//更新当前选中值
                                    return its
                                })
                                setxaxis((xaxis) => {
                                    let newx = [...xaxis];
                                    newx = newx.map(it => {
                                        if (it.name == record.name) {
                                            it.type = !record.type;
                                        }
                                        return it
                                    })

                                    return newx
                                })

                            }} />
                        </Tooltip>
                    }
                },
                {
                    title: "名称",
                    dataIndex: "name",
                    key: "name",
                    width: 100,
                    editable: false

                },
                {
                    title: "值",
                    dataIndex: "value",
                    key: "value",
                    valueType: (record) => {
                        return record.type ? "select" : "input"
                    },
                    request: () => {
                        return bianliang.map(its => ({
                            label: its.variable_name,
                            value: `{{${its.variable_name}}}`
                        }))
                    }

                },
            ],
            "rowKey": "name",
            "rowName": "name",
            "onChange": (value) => {
                setxaxis(value)
            }
        }
    }, [xaxis])


    return <div>
        <p className={styles.title} style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span>
                雷达图设置
            </span>
        </p>
        <Divider style={{ marginTop: 0, marginBottom: 12 }}></Divider>

        <InitForm
            style={{ marginTop: -24 }}
            fields={{
                "backgroundColor": {
                    "value": backgroundColor,
                    "type": "colorpicker",
                    "title": "区块背景",
                    "name": [
                        "backgroundColor"
                    ],
                    "transparent": true,
                    "required": false
                },
                "borderRadius": {
                    "value": borderRadius,
                    "type": "slider",
                    "title": "区块圆角",
                    "name": [
                        "borderRadius"
                    ],
                    "max": 400,
                    "required": false
                },
            }}
            col={{ span: 24 }}
            actions={() => null}
            onChange={(val, vals) => {
                refreshconfig((its) => {
                    its.style = {
                        ...its.style,
                        backgroundColor: vals.backgroundColor,
                        borderRadius: vals.borderRadius
                    }
                    setInitialState(s => ({ ...s, componentConfig: its }))//更新当前选中值
                    return its
                })
            }}

        ></InitForm>

        <div style={{ margin: "-36px 0px 0 0px" }}>
            <b style={{ color: "#000" }} className='spread'>
                <span>编辑数据</span>
            </b>
            <Tabs
                activeKey={activeKey}
                tabBarGutter={12}
                onChange={(index) => {
                    setactiveKey(index)
                }}
                tabBarExtraContent={{
                    right: <Tooltip title={"添加维度(雷达图上的区块)"} placement="topRight">
                        <Button size='small' type='primary' icon={<PlusOutlined />} onClick={() => {
                            refreshconfig(vals => {
                                vals.option.color.push("#666666");
                                vals.option.series[0]["data"].push({
                                    value: [30, 12, 68, 58, 99, 95],
                                    name: '新增',
                                    areaStyle: {
                                        color: "#666666"
                                    }
                                })
                                setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                                return vals
                            })
                        }} />
                    </Tooltip>
                }}
            >
                <TabPane
                    tab={<a>编辑X轴</a>}
                    key={"Y"}
                    active={false}
                >
                    <EditTable {...edittablepropsy}></EditTable>
                </TabPane>
                {
                    series[0]["data"] ? series[0]["data"].map((item, index) => {
                        return <TabPane
                            tab={<div className='center'>
                                {item.name}
                                {
                                    index == 0 ? null : <Popconfirm
                                        title="是否删除该维度"
                                        okText="删除"
                                        onConfirm={() => {
                                            refreshconfig(vals => {
                                                vals.option = {
                                                    ...vals.option,
                                                    color: vals.option.color?.filter((a, i) => i != index),
                                                    series: vals.option.series.map((its, ins) => {
                                                        its.data = its.data?.filter((a, i) => i != index)
                                                        return its
                                                    })
                                                }
                                                setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                                                return JSON.parse(JSON.stringify(vals))
                                            })
                                            setactiveKey((s) => {
                                                let news = parseInt(s);
                                                return news == 0 ? "0" : (news - 1).toString();
                                            })
                                        }}
                                    >
                                        <CloseOutlined style={{ margin: 0, marginLeft: 6, fontSize: 12 }}>
                                        </CloseOutlined>
                                    </Popconfirm>
                                }

                            </div>}
                            key={index}>
                            <label htmlFor="titles" style={{ margin: "0 0 12px 0", display: "block" }}>维度/区块名称</label>
                            <Input
                                name="titles"
                                value={item.name}
                                onChange={e => {
                                    let val = e.target.value;
                                    refreshconfig((vals) => {
                                        vals.option = {
                                            ...vals.option,
                                            series: series.map((it, i) => {
                                                it.data = it.data?.map((its, ins) => {
                                                    if (ins == index) {
                                                        its.name = val
                                                    }
                                                    return its;
                                                })

                                                return it
                                            })
                                        }
                                        setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                                        return vals
                                    })
                                }} />
                            <label style={{ margin: "12px 0 12px 0", display: "block" }}>区块颜色</label>
                            <Colorpicker
                                value={color[index]}
                                style={{ marginBottom: 28 }}
                                onChange={val => {
                                    refreshconfig((vals) => {
                                        vals.option = {
                                            ...vals.option,
                                            color: color.map((it, i) => {
                                                if (i == index) {
                                                    it = val
                                                }
                                                return it
                                            }),
                                            series: series.map((it, i) => {
                                                it.data = it.data?.map((its, ins) => {
                                                    if (ins == index) {
                                                        its.areaStyle.color = val
                                                    }
                                                    return its;
                                                })

                                                return it
                                            })
                                        }
                                        setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                                        return vals
                                    })
                                }} />

                            <EditTable {...edittableprops}></EditTable>
                        </TabPane>
                    }) : null
                }

            </Tabs>

        </div>




    </div>
}

function Picture({ config, setconfig, initialState, setInitialState, bianliang }) {
    const { componentConfig } = initialState,
        { imgurl, edit, imgrotate, imgzoom } = componentConfig ?? {},
        { borderRadius } = componentConfig?.style ?? {};

    function refreshconfig(fn) {
        setconfig((config) => {
            let newconfig = JSON.parse(JSON.stringify(config));
            newconfig.pages = newconfig?.pages?.map?.(item => {
                if (item.active) {
                    item.components = item?.components?.map?.(its => {
                        if (its.id == componentConfig.id) {
                            return fn?.(its);
                        }
                        return its;
                    })
                }
                return item
            });
            return newconfig
        });
    }

    let refreshsizeurl = async (url) => {
        let percent = await loadImageSize(url);
        refreshconfig(vals => {
            // 图片地址
            vals.imgurl = url;

            vals.style = {
                ...vals.style,
                height: (vals.style.width) * percent
            };
            vals.imgstyle = {
                ...vals.imgstyle,
                height: (vals.style.width) * percent
            };
            setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
            return vals
        })
    }


    return (
        <div>
            <p className={styles.title} style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span>
                    图片设置
                </span>
            </p>
            <Divider style={{ marginTop: 0, marginBottom: 12 }}></Divider>

            <Tabs defaultActiveKey="1" onChange={() => { }}>
                <TabPane tab="本地上传" key="1">
                    <UploadImage imgurl={imgurl} setimgurl={(url) => {
                        refreshsizeurl(url)
                    }} />
                </TabPane>
                <TabPane tab="网络图片" key="2">
                    <Input
                        placeholder='网络图片地址'
                        value={imgurl}
                        allowClear={true}
                        onChange={(e) => {
                            let url = e.target.value;
                            refreshsizeurl(url)
                        }}
                    ></Input>
                </TabPane>
            </Tabs>

            <p className='spread' style={{ marginTop: 12, color: "rgba(0, 0, 0, 0.85)" }}>
                <span>
                    裁切图片
                </span>
            </p>

            <p className='spread' style={{ marginTop: 12, padding: "0 6px" }}>
                <Switch checked={edit == true} onChange={(checked) => {
                    refreshconfig(vals => {
                        vals.edit = checked;
                        setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                        return vals
                    })
                }}></Switch>
                <span style={{ color: "#999" }}>
                    {edit ? "裁切中" : "待裁切"}
                </span>
            </p>
            <InitForm
                style={{ marginTop: -24 }}
                fields={{
                    "imgzoom": {
                        "value": imgzoom,
                        "type": "slider",
                        "title": "缩放比例",
                        "name": [
                            "imgzoom"
                        ],
                        "max": 20,
                        "min": 0.25,
                        "step": 0.25,
                        "required": false,
                        "hides":!edit
                    },
                    "imgrotate": {
                        "value": imgrotate,
                        "type": "slider",
                        "title": "旋转角度",
                        "name": [
                            "imgrotate"
                        ],
                        "max": 365,
                        "min": 1,
                        "required": false,
                        "hides":!edit
                    },
                    "borderRadius": {
                        "value": borderRadius,
                        "type": "slider",
                        "title": "区块圆角",
                        "name": [
                            "borderRadius"
                        ],
                        "max": 400,
                        "required": false
                    },
                }}
                col={{ span: 24 }}
                actions={() => null}
                onChange={(val, vals) => {
                    refreshconfig((its) => {
                        its.style = {
                            ...its.style,
                            borderRadius: vals.borderRadius
                        }
                        its.imgzoom = vals.imgzoom;
                        its.imgrotate = vals.imgrotate
                        setInitialState(s => ({ ...s, componentConfig: its }))//更新当前选中值
                        return its
                    })
                }}

            ></InitForm>

        </div>
    );
}

function Dashed({ config, setconfig, initialState, setInitialState }) {
    const { componentConfig } = initialState,
        { borderBottomWidth, borderBottomColor, width, rotate } = componentConfig?.style ?? {};


    return <div>
        <p className={styles.title} style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span>
                虚线设置
            </span>
        </p>
        <Divider style={{ marginTop: 0, marginBottom: 12 }}></Divider>
        <InitForm
            style={{ marginTop: -24 }}
            fields={{
                "rotate": {
                    "value": rotate,
                    "type": "slider",
                    "title": "旋转角度",
                    "name": [
                        "rotate"
                    ],
                    "max": 360,
                    "required": false
                },
                "borderBottomWidth": {
                    "value": borderBottomWidth,
                    "type": "slider",
                    "title": "虚线粗细",
                    "name": [
                        "borderBottomWidth"
                    ],
                    "required": false
                },
                "borderBottomColor": {
                    "value": borderBottomColor,
                    "type": "colorpicker",
                    "title": "虚线颜色",
                    "name": [
                        "borderBottomColor"
                    ],
                    "required": false
                },
                "width": {
                    "value": width,
                    "type": "slider",
                    "title": "虚线长度",
                    "name": [
                        "width"
                    ],
                    "max": 3000,
                    "required": false
                },
            }}
            col={{ span: 24 }}
            actions={() => null}
            onChange={(val, vals) => {
                setconfig((config) => {
                    let newconfig = JSON.parse(JSON.stringify(config));
                    newconfig.pages = newconfig?.pages?.map?.(item => {
                        if (item.active) {
                            item.components = item?.components?.map?.(its => {
                                if (its.id == componentConfig.id) {
                                    its.style = {
                                        ...its.style,
                                        ...val,
                                        height: val.borderBottomWidth * 2
                                    }
                                    setInitialState(s => ({ ...s, componentConfig: its }))//更新当前选中值
                                }
                                return its;
                            })
                        }
                        return item
                    });
                    return newconfig
                });
            }}

        ></InitForm>
    </div>
}

function Arrow({ config, setconfig, initialState, setInitialState }) {
    const { componentConfig } = initialState,
        { rotate, color } = componentConfig?.style ?? {};


    return <div>
        <p className={styles.title} style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span>
                箭头设置
            </span>
        </p>
        <Divider style={{ marginTop: 0, marginBottom: 12 }}></Divider>
        <InitForm
            style={{ marginTop: -24 }}
            fields={{
                "rotate": {
                    "value": rotate,
                    "type": "slider",
                    "title": "旋转角度",
                    "name": [
                        "rotate"
                    ],
                    "max": 360,
                    "required": false
                },
                "color": {
                    "value": color,
                    "type": "colorpicker",
                    "title": "箭头颜色",
                    "name": [
                        "color"
                    ],
                    "required": false
                },
            }}
            col={{ span: 24 }}
            actions={() => null}
            onChange={(val, vals) => {
                setconfig((config) => {
                    let newconfig = JSON.parse(JSON.stringify(config));
                    newconfig.pages = newconfig?.pages?.map?.(item => {
                        if (item.active) {
                            item.components = item?.components?.map?.(its => {
                                if (its.id == componentConfig.id) {
                                    its.style = {
                                        ...its.style,
                                        ...val,
                                    }
                                    setInitialState(s => ({ ...s, componentConfig: its }))//更新当前选中值
                                }
                                return its;
                            })
                        }
                        return item
                    });
                    return newconfig
                });
            }}

        ></InitForm>
    </div>
}

function Square({ config, setconfig, initialState, setInitialState }) {
    const { componentConfig } = initialState,
        { backgroundColor, borderRadius } = componentConfig?.style ?? {};


    return <div>
        <p className={styles.title} style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span>
                矩形设置
            </span>
        </p>
        <Divider style={{ marginTop: 0, marginBottom: 12 }}></Divider>
        <InitForm
            style={{ marginTop: -24 }}
            fields={{
                "backgroundColor": {
                    "value": backgroundColor,
                    "type": "colorpicker",
                    "title": "区块背景",
                    "name": [
                        "backgroundColor"
                    ],
                    "transparent": true,
                    "required": false
                },
                "borderRadius": {
                    "value": borderRadius,
                    "type": "slider",
                    "title": "区块圆角",
                    "name": [
                        "borderRadius"
                    ],
                    "max": 400,
                    "required": false
                }
            }}
            col={{ span: 24 }}
            actions={() => null}
            onChange={(val, vals) => {
                setconfig((config) => {
                    let newconfig = JSON.parse(JSON.stringify(config));
                    newconfig.pages = newconfig?.pages?.map?.(item => {
                        if (item.active) {
                            item.components = item?.components?.map?.(its => {
                                if (its.id == componentConfig.id) {
                                    its.style = {
                                        ...its.style,
                                        ...val
                                    }
                                    setInitialState(s => ({ ...s, componentConfig: its }))//更新当前选中值
                                }
                                return its;
                            })
                        }
                        return item
                    });
                    return newconfig
                });
            }}

        ></InitForm>
    </div>
}


function Atable({ config, setconfig, initialState, setInitialState, bianliang }) {
    const { componentConfig, selectedKeys } = initialState,
        { borderColor, borderWidth, borderRadius, align, bodybg, bodysize, bodycolor } = componentConfig?.style ?? {},
        { edit } = componentConfig;


    function refreshconfig(fn) {
        setconfig((config) => {
            let newconfig = JSON.parse(JSON.stringify(config));
            newconfig.pages = newconfig?.pages?.map?.(item => {
                if (item.active) {
                    item.components = item?.components?.map?.(its => {
                        if (its.id == componentConfig.id) {
                            return fn?.(its);
                        }
                        return its;
                    })
                }
                return item
            });
            return newconfig
        });
    }


    return <div>
        <p className={styles.title} style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span>
                表格设置
            </span>
        </p>

        <Divider style={{ marginTop: 0, marginBottom: 12 }}></Divider>
        <p className='spread' style={{ marginTop: 12, color: "rgba(0, 0, 0, 0.85)" }}>
            <span>
                编辑表格
            </span>
        </p>
        <p className='spread' style={{ marginTop: 12, padding: "0 6px", borderBottom: "6px solid #fafafa", paddingBottom: 12, marginBottom: 12 }}>
            <Switch checked={edit == true} onChange={(checked) => {
                refreshconfig(vals => {
                    vals.edit = checked;
                    setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                    return vals
                })
            }}></Switch>
            <span style={{ color: "#999" }}>
                {edit ? "编辑中" : "待编辑"}
            </span>
        </p>

        <div className="spread" style={{ marginBottom: 20 }}>
            <Button
                type='primary'
                onClick={() => {
                    let time = moment().valueOf();
                    refreshconfig(vals => {
                        let { row, col } = vals.rowcol;
                        let newarr = [...vals.dataSource];
                        vals.rowcol = {
                            ...vals.rowcol,
                            col: col + 1
                        }
                        new Array(row).fill("").map((it, i) => {
                            let idlist = newarr.map((it, i) => i + 1),
                                idmax = Math.max(...idlist) ?? 0;
                            let len = (idmax + 1).toString() + vals.addsub + time,
                                ins = (col * (i + 1)) + (i);
                            newarr.splice(ins, 0, {
                                content: "内容",
                                id: len,
                                style: {
                                    color: "#000000",
                                    backgroundColor: "#FFFFFF",
                                    fontSize: 16
                                }
                            })
                        })
                        vals.dataSource = newarr;
                        setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值
                        return vals
                    })
                }}
            >
                新增列
            </Button>
            <Button
                type='primary'
                ghost
                style={{ flex: 1, marginLeft: 12 }}
                onClick={() => {
                    let time = moment().valueOf();
                    refreshconfig(vals => {
                        let { row, col } = vals.rowcol;
                        let newarr = [...vals.dataSource];
                        vals.rowcol = {
                            ...vals.rowcol,
                            row: row + 1
                        }
                        vals.style = {
                            ...vals.style,
                            height: 68 * (row + 2),
                        }
                        new Array(col).fill("").map((it, i) => {
                            let idlist = newarr.map((it, i) => i + 1),
                                idmax = Math.max(...idlist) ?? 0;
                            let len = (idmax + 1).toString() + vals.addsub + time;
                            newarr.push({
                                content: "内容",
                                id: len,
                                style: {
                                    color: "#000000",
                                    backgroundColor: "#FFFFFF",
                                    fontSize: 16
                                }
                            })
                        })
                        vals.dataSource = newarr;
                        setInitialState(s => ({ ...s, componentConfig: vals }))//更新当前选中值

                        return vals
                    })
                }}
            >
                新增行
            </Button>
        </div>



        <InitForm
            style={{ marginTop: -24 }}
            fields={{
                "bodybg": {
                    "value": bodybg ?? "#ffffff",
                    "type": "colorpicker",
                    "title": "选中表格的背景色",
                    "name": [
                        "bodybg"
                    ],
                    "transparent": true,
                    "required": false,
                    "hides": (!selectedKeys || selectedKeys.length == 0)
                },
                "bodycolor": {
                    "value": bodycolor ?? "#000000",
                    "type": "colorpicker",
                    "title": "选中表格的文字颜色",
                    "name": [
                        "bodycolor"
                    ],
                    "transparent": true,
                    "required": false,
                    "hides": (!selectedKeys || selectedKeys.length == 0)
                },
                "bodysize": {
                    "value": bodysize ?? 14,
                    "type": "slider",
                    "title": "选中表格的文字大小",
                    "name": [
                        "bodysize"
                    ],
                    "min": 1,
                    "required": false,
                    "hides": (!selectedKeys || selectedKeys.length == 0)
                },
                "borderColor": {
                    "value": borderColor ?? "#f0f0f0",
                    "type": "colorpicker",
                    "title": "表格边框颜色",
                    "name": [
                        "borderColor"
                    ],
                    "transparent": true,
                    "required": false
                },
                "borderWidth": {
                    "value": borderWidth ?? 1,
                    "type": "slider",
                    "title": "表格边框宽度",
                    "name": [
                        "borderWidth"
                    ],
                    "max": 400,
                    "min": 1,
                    "required": false
                },
                "borderRadius": {
                    "value": borderRadius ?? 8,
                    "type": "slider",
                    "title": "表格圆角",
                    "name": [
                        "borderRadius"
                    ],
                    "max": 400,
                    "required": false
                },
                "align": {
                    "value": align ?? "flex-start",
                    "type": "radio",
                    "title": "文字位置",
                    "name": [
                        "align"
                    ],
                    "required": false,
                    "options": [
                        {
                            label: "左",
                            value: "flex-start"
                        },
                        {
                            label: "中",
                            value: "center"
                        },
                        {
                            label: "右",
                            value: "flex-end"
                        }
                    ]
                }
            }}
            col={{ span: 24 }}
            actions={() => null}
            onChange={(val, vals) => {
                refreshconfig((its) => {
                    its.style = {
                        ...its.style,
                        ...val
                    }
                    its.dataSource = its.dataSource.map((it, i) => {
                        if (selectedKeys.indexOf(it.id) > -1) {
                            const { backgroundColor, fontSize, color } = it["style"] ?? {};
                            it["style"] = {
                                ...it["style"],
                                backgroundColor: val.bodybg ?? backgroundColor,
                                fontSize: val.bodysize ?? fontSize,
                                color: val.bodycolor ?? color
                            }
                        } else {
                        }
                        return it
                    })
                    setInitialState(s => ({ ...s, componentConfig: its }))//更新当前选中值
                    return its;
                })
            }}

        ></InitForm>
    </div>
}


let components = {
    Canvas,
    Rowtext,
    Columntext,
    Linechart,
    Barchart,
    Picture,
    Radarchart,
    Dashed,
    Arrow,
    Square,
    Atable
}


function Atempconfig({ config, setconfig }) {
    const { initialState, setInitialState } = useModel("@@initialState");
    const { data, loading } = useRequest(() => {
        if (config.id) {
            return getFetch({ url: "/api/template/variable_list", params: { id: config.id } })
        } else {
            return {}
        }
    }, {
        refreshDeps: [config.id]
    })

    return (
        <div className={styles.containers}>
            <Scrollbars
                thumbMinSize={10}
                autoHide
                style={{ width: '110%', height: "100%" }}
                hideTracksWhenNotNeeded={true}
            >
                <div style={{ width: 276, userSelect: "none" }}>
                    {React.createElement(components[initialState.component], { config, setconfig, initialState, setInitialState, bianliang: data?.data?.dataList })}
                </div>
            </Scrollbars>
        </div>
    )



}



export default Atempconfig